<template>
    <div class="package_wrapper">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 专栏 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-button type="primary" class="handle-del mr10" @click="addDialog">新增专栏</el-button>
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除 </el-button>
                <el-input v-model="query.keyword" placeholder="输入专栏名称" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                :data="tableData"
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column label="专栏封面" width="100">
                    <template slot-scope="scope">
                        <img :src="scope.row.cover" @error="tabErrorPicture(scope.row.id,'tableData')" alt="" class="info-image" />
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="专栏名称"></el-table-column>
                <el-table-column prop="description" label="专栏描述"></el-table-column>
                <el-table-column label="免费/付费">
                    <template slot-scope="scope">
                        <span style="color: #e65c5c">{{ scope.row.price == 0 ? '免费' : '¥ ' + scope.row.price }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="f_view" label="浏览量"></el-table-column>
                <el-table-column prop="f_sales" label="订阅量"></el-table-column>
                <el-table-column prop="f_favorites" label="收藏量"></el-table-column>
                <el-table-column label="操作" width="450" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button @click="addDownDialog(scope.row.id, scope.row.title)" type="primary" size="mini">添加下载资料</el-button>
                        <el-button @click="openColumnManage(scope.row.id, scope.row.title, scope.row.knowledge_ids)" type="primary" size="mini">专栏内容管理</el-button>
                        <el-button @click="edit(scope.row.id, scope.row)" type="success" size="mini">编辑</el-button>
                        <el-button @click="putOn(scope.row.id, scope.row.status)" type="warning" size="mini">{{ scope.row.status == 0 ? '上架' : '下架' }}</el-button>
                        <el-button @click="deleteRow(scope.row.id, scope.$index)" type="danger" size="mini">删除 </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.page"
                    :page-size="query.rows"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
        <!-- 新增专栏弹出框 -->
        <uploadimage ref="uploadimagecom" v-on:childByImageValue="childByImageValue"></uploadimage>
        <el-dialog title="新增/编辑专栏" @close="cancel" :visible.sync="showDialog" width="50%">
            <el-form ref="form" :model="form" :rules="rules" label-width="125px">
                <el-form-item label="专栏名称" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="专栏描述" prop="description">
                    <el-input type="textarea" :rows="2" v-model="form.description"> </el-input>
                </el-form-item>
                <el-form-item label="专栏封面" prop="cover">
                    <div class="avatar-uploader" @click="showUploadImage('videofm')">
                        <img v-if="form.cover" :src="form.cover" class="avatar" height="200px" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </div>
                    <div class="el-upload__tip">封面建议尺寸：800*600px，支持jpg、png</div>
                </el-form-item>
                <el-form-item label="分类" prop="category_id">
                    <el-select v-model="form.category_id" clearable placeholder="请选择专栏分类" v-if="!category_length">
                        <!-- <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.id"> </el-option> -->
                        <el-option-group v-for="group in options" :key="group.id" :label="group.title">
						      <el-option v-for="item in group._child" :key="item.id" :label="item.title" :value="item.id">
						      </el-option>
						</el-option-group>
                    </el-select>

                    <a href="/classification" class="data-overview-item__num" v-if="category_length">暂无分类，请前往创建</a>
                </el-form-item>
                <el-form-item label="会员专享">
                    <el-checkbox :true-label="1" :false-label="0" v-model="form.only_member">勾选后仅会员可订阅</el-checkbox>
                </el-form-item>
                <el-form-item label="是否付费">
                    <el-radio-group v-model="form.expense" @change="course_price">
                        <el-radio :label="0">免费</el-radio>
                        <el-radio :label="1">付费</el-radio>
                    </el-radio-group>
                    <div v-if="form.expense == 1">
                        <el-form-item label="商品价格">
                            <el-input v-model="form.price" class="showPay"></el-input><span>元</span>
                        </el-form-item>
                        <el-form-item label="划线价格">
                            <el-input v-model="form.marking_price" class="showPay"></el-input><span>元</span>
                        </el-form-item>
                    </div>
                </el-form-item>
                <el-form-item label="返还积分">
                    <el-input v-model="form.score"></el-input>
                </el-form-item>
                <el-form-item label="订阅后自定义内容">
                    <quill-editor v-model="form.custom_desc"></quill-editor>
                </el-form-item>
                <el-form-item label="完整内容">
                    <quill-editor v-model="form.content"></quill-editor>
                </el-form-item>
                <el-form-item label="选择讲师" prop="teacher_id">
                    <el-button @click="chooseLecturer" type="primary" size="mini">选择讲师</el-button>
                    <el-table
                        :data="selectRowData"
                        v-if="selectRowData.length !== 0"
                        class="table"
                        ref="multipleTable"
                        header-cell-class-name="table-header"
                    >
                        <el-table-column label="讲师图片">
                            <template slot-scope="scope">
                                <img :src="scope.row.cover"  @error="tabErrorPicture(scope.row.id,'selectRowData')" alt="" class="info-image" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="讲师姓名"></el-table-column>
                        <el-table-column prop="description" label="讲师描述"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <el-button @click="del_lecturer" type="danger" size="mini">移除讲师</el-button>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="自定义浏览量">
                    <el-input v-model="form.f_view"></el-input>
                </el-form-item>
                <el-form-item label="自定义订阅量">
                    <el-input v-model="form.f_sales"></el-input>
                </el-form-item>
                <el-form-item label="自定义收藏量">
                    <el-input v-model="form.f_favorites"></el-input>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input v-model="form.sort"></el-input>
                </el-form-item>
                <el-form-item label="状态设置">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">立即上架</el-radio>
                        <el-radio :label="0">暂不上架</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save('form')">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 讲师弹框 -->
        <el-dialog width="500px" title="选择讲师" @close="exit" :visible.sync="innerVisible" append-to-body>
            <el-form ref="form" :model="form">
                <el-form-item>
                    <el-input v-model="query.keyword" placeholder="输入讲师姓名" class="handle-input" style="margin: 0 10px 0 0;"></el-input>
                    <el-button type="primary" icon="el-icon-search" @click="lecturerSearch">搜索</el-button>
                </el-form-item>
                <el-table
                    :data="chooseLecturerTableData"
                    @row-click="chooseRow"
                    class="chooseLecturerTable"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                >
                    <el-table-column prop="name" label="讲师图片">
                        <template slot-scope="scope">
                            <!-- <img :src="scope.row.cover" alt="" class="" /> -->
                            <img :src="scope.row.cover" @error="tabErrorPicture(scope.row.id,'chooseLecturerTableData')" alt="" class="info-image" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="讲师姓名"></el-table-column>
                    <el-table-column prop="description" label="讲师描述"></el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.page"
                        :page-size="query.rows"
                        :total="lecturerListTotal"
                        @current-change="lecturerPageChange"
                    >
                    </el-pagination>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="exit">关 闭</el-button>
            </span>
        </el-dialog>
        <!-- 预览弹出框 -->
        <el-dialog :title="title" :visible.sync="previewDialogVisible" width="300px">
            <div class="preview">
                <h3>微信扫码预览</h3>
                <qriously class="qrCode" :value="preview_url" :size="200" :backgroundAlpha="1" />
                <el-input v-model="preview_url">
                    <template slot="prepend">SPA版url</template>
                    <el-button
                        v-clipboard="copy_value"
                        v-clipboard:success="clipboardSuccessHandler"
                        v-clipboard:error="clipboardErrorHandler"
                        slot="append"
                        >复制</el-button
                    >
                </el-input>
            </div>
        </el-dialog>
        <el-dialog :title="title" :visible.sync="downDialogVisible" width="600px">
            <el-form ref="fileform" :model="fileform">
                <el-form-item>
                    <el-button type="danger" @click="removeDownFile">批量移除</el-button>
                    <el-button type="primary" @click="addDownFile" class="mr-10">添加下载资料</el-button>
                    <el-input
                        v-model="addFile.keyword"
                        placeholder="输入试卷名称"
                        class="handle-input mr10"
                        style="width: 200px"
                    ></el-input>
                    <el-button type="primary" icon="el-icon-search" @click="addFileSearch">搜索</el-button>
                </el-form-item>
                <el-table
                    :data="fileTableData"
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleFileSelectionChange"
                >
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column label="资料类型">
                        <template slot-scope="scope">
                            <img :src="scope.row.src" v-if="scope.row" @error="tabErrorPicture(scope.row.id,'fileTableData')" alt="" class="info-image" />
                            
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="资料名称">
                        <template slot-scope="scope">
                            {{ scope.row ? scope.row.name : '' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="移除资料">
                        <template slot-scope="scope">
                            <el-button type="danger" v-if="scope.row" @click="removeOneFile(scope.row.id)">移除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="addFile.page"
                        :page-size="addFile.rows"
                        :total="filePageTotal"
                        @current-change="filePageChange"
                    ></el-pagination>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="downDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="downDialogVisible = false">保存</el-button>
            </span>
        </el-dialog>
        <uploadfiles ref="uploadfilescom" v-on:childByFilesValue="childByFilesValue"></uploadfiles>
    </div>
</template>

<script>
import uploadimage from '@/components/common/uploadimage.vue';
import uploadfiles from '@/components/common/uploadfiles.vue';
import showfileMixin from '@/mixin/showossfile.js';
import {
    classifyListData,
    lecturerListData,
    columnListData,
    addColumnData,
    delColumnData,
    addColumnDownFile,
    getColumnDownFile,
    searchColumnDownFile,
    removeFile
} from '../../api/index';
export default {
    name: 'lecturer',
    components: {
        uploadimage,
        uploadfiles
    },
    mixins: [showfileMixin],
    data() {
        return {
            category_length: false,
            fileform: {
                id: '',
                name: '',
                src: ''
            },
            addFile: {
                page: 1,
                rows: 4,
                keyword: ''
            },
            query: {
                status: 0,
                page: Number(localStorage.getItem('packagelastpage') ? localStorage.getItem('packagelastpage') : 1),
                rows: 4,
                keyword: ''
            },
            //pictureList: [],
            title: '',
            preview_url: '',
            copy_value: '',
            form: {
                id: '',
                teacher_id: '',
                title: '',
                description: '',
                cover: '',
                category_id: '',
                only_member: '',
                expense: '',
                price: '',
                marking_price: '',
                score: '',
                custom_desc: '',
                content: '',
                f_view: '',
                f_sales: '',
                f_favorites: '',
                sort: '',
                status: 1
            },
            rules: {
                title: [
                    { required: true, message: '请输入专栏名称', trigger: 'blur' },
                    { min: 1, max: 30, message: '长度在1到30个字符', trigger: 'blur' }
                ],
                // teacher_id: [{ required: true, message: '请选择讲师', trigger: 'blur' }],
                category_id: [{ required: true, message: '请选择分类', trigger: 'change' }]
            },
            options: [
                {
                    id: '1',
                    title: '黄金糕',
                    _child: [
                        {
                            id: '6',
                            title: '测试'
                        }
                    ]
                }
            ],
            // options_child: [],
            tableData: [],
            multipleSelection: [],
            multipleFileSelection: [],
            delList: [],
            chooseLecturerTableData: [],
            selectRowData: [],
            showDialog: false,
            innerVisible: false,
            previewDialogVisible: false,
            pageTotal: 0,
            lecturerListTotal: 0,
            downDialogVisible: false,
            fileTableData: [],
            filePageTotal: 0,
            column_id: '',
            errorProduct: require('@/assets/img/noProduct.jpg'), 
        };
    },
    created() {
        this.getData();
    },
    methods: {
        tabErrorPicture(id,data){    // 表格图文封面默认展示图
            let i = this[data].findIndex(v => v.id == id);
			this[data][i].cover = this.errorProduct;
        },
        removeOneFile(id) {
            removeFile({ id, column_id: this.column_id }).then((res) => {
                if (res.code == 1) {
                    this.getFileTableData();
                    this.$message.success('移除下载文件成功');
                } else if (res.code == 2) {
                    this.fileTableData = [];
                } else {
                    this.$message.error('移除下载文件失败');
                }
            });
        },
        removeDownFile() {
            let arr = [];
            for (let item of this.multipleFileSelection) {
                arr.push(item.id);
            }
            removeFile({ id: arr.toString(), column_id: this.column_id }).then((res) => {
                console.log(res);
                if (res.code == 1) {
                    this.getFileTableData();
                    this.$message.success('移除下载文件成功');
                } else if (res.code == 2) {
                    this.fileTableData = [];
                } else {
                    this.$message.error('移除下载文件失败');
                }
            });
            this.getFileTableData();
        },
        addDownFile() {
            this.$refs.uploadfilescom.isone = false;
            this.$refs.uploadfilescom.dialogVisible = true; //显示上传对话框
        },
        getFileTableData() {
            getColumnDownFile(this.addFile).then((res) => {
                if (res.code == 1) {
                    this.fileTableData = res.data.list;
                    this.filePageTotal = res.data.count;
                }
            });
        },
        filePageChange(val) {
            this.$set(this.addFile, 'page', val);
            this.getFileTableData();
        },
        addFileSearch() {
            this.addFile.column_id = this.column_id;
            searchColumnDownFile(this.addFile).then((res) => {
                if (res.code == 1) {
                    this.fileTableData = res.data.list;
                    this.filePageTotal = res.data.count;
                }
            });
        },
        addDownDialog(id, title) {
            this.column_id = id;
            this.title = title;
            this.downDialogVisible = true;
            this.addFile.column_id = id;
            getColumnDownFile(this.addFile).then((res) => {
                if (res.code == 1) {
                    this.fileTableData = res.data.list;
                    this.filePageTotal = res.data.count;
                }
            });
        },
        getData() {
            columnListData(this.query).then((res) => {
                console.log(res);
                this.tableData = res.data.list;
                this.pageTotal = res.data.count;
            });
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        handleFileSelectionChange(val) {
            this.multipleFileSelection = val;
        },
        //批量删除
        delAllSelection() {
            if (this.multipleSelection.length > 0) {
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    const length = this.multipleSelection.length;
                    let str = '';
                    let strID = '';
                    this.delList = this.delList.concat(this.multipleSelection);
                    console.log(this.delList);
                    for (let i = 0; i < length; i++) {
                        str += this.multipleSelection[i].title + ' ';
                        strID += this.multipleSelection[i].id + ',';
                    }
                    delColumnData({
                        id: strID.substring(0, strID.lastIndexOf(','))
                    }).then((res) => {
                        if (res.code == 1) {
                            this.$message.success(`删除了${str}`);
                            this.multipleSelection = [];
                            this.getData();
                            //location.reload();
                        }
                    });
                });
            }else{
				this.$message.error('请点击左侧选中需要删除的内容');
			}
        },
        // 搜索
        handleSearch() {
            this.$set(this.query);
            this.getData();
        },
        // 讲师搜索
        lecturerSearch() {
            this.chooseLecturer();
        },
        // 分页
        handlePageChange(val) {
            this.$set(this.query, 'page', val);
            this.getData();
        },
        // 讲师分页
        lecturerPageChange(val) {
            this.$set(this.query, 'page', val);
            this.chooseLecturer();
        },
        // 改变价格
        course_price(v) {
            if (v == 0) {
                this.form.price = '';
                this.form.marking_price = '';
            }
        },
        //新增
        addDialog() {
            this.showDialog = true;
            this.selectRowData = [];
            classifyListData().then((res) => {
                this.options = res.data.list;
                if (res.data.list.length > 0) {
                    this.category_length = false;
                } else {
                    this.category_length = true;
                }
            });
        },
        chooseLecturer() {
            this.innerVisible = true;
            lecturerListData(this.query).then((res) => {
                this.chooseLecturerTableData = res.data.list;
                this.lecturerListTotal = res.data.count;
            });
        },
        chooseRow(row) {
            this.selectRowData = [];
            this.selectRowData.push(row);
            this.form.teacher_id = row.id;
            this.innerVisible = false;
        },
        del_lecturer() {
            this.selectRowData = [];
            this.form.teacher_id = '';
        },
        // 预览
        preview(id, title) {
            this.previewDialogVisible = true;
            this.title = title;
            this.copy_value = this.preview_url = `${this.$front.FrontUrl}/xuejing/product/${localStorage.getItem(domainname)}?id=${id}`;
        },
        clipboardSuccessHandler({ value, event }) {
            this.$message.success('复制成功');
        },
        clipboardErrorHandler({ value, event }) {
            console.log('复制失败', value);
        },
        openColumnManage(id, title, ids) {
            //打开视频内容管理
            localStorage.setItem('moreids', ids);
            localStorage.setItem('column_id', id);
            localStorage.setItem('title', title);
            this.$router.push(`/courseList/columnManage`);
        },
        //编辑
        edit(id, row) {
            classifyListData().then((res) => {
                this.options = res.data.list;
            });
            this.selectRowData = [];
            this.showDialog = true;
            this.form = row;
            //this.form.name=row.teacher_info.name;
            this.selectRowData.push(row.teacher_info);
        },
        //上下架
        putOn(id, status) {
            this.$confirm(`确定${status == 0 ? '上架' : '下架'}吗！`, '提示', {
                type: 'warning'
            }).then(() => {
                addColumnData({
                    id: id,
                    status: status == 0 ? 1 : 0
                }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success('成功');
                        this.getData();
                        //location.reload();
                    }
                });
            });
        },
        //删除
        deleteRow(id, index) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                delColumnData({ id }).then((res) => {
                    console.log(res);
                    if (res.code == 1) {
                        this.$message.success('删除成功');
                        this.tableData.splice(index, 1);
                        //location.reload();
                    } else {
                        this.$message.success('删除失败');
                    }
                });
            });
        },
        //取消
        cancel() {
            this.form = {};
            //this.pictureList = [];
            this.showDialog = false;
        },
        //关闭
        exit() {
            this.innerVisible = false;
        },
        //确定
        save(formName) {
            // let formData = new FormData();
            // formData.append('cover', this.cover);
            // formData.append('column', this.column);
            // formData.append("form", JSON.stringify(this.form));
			
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    addColumnData(this.form).then((res) => {
                        if (res.code == 1) {
                            this.showDialog = false;
                            localStorage.setItem('packagelastpage', this.query.page);
                            this.$message.success('操作成功');
                            setTimeout(() => {
                                this.getData();
                                //location.reload();
                            }, 200);
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        showUploadImage(action) {
            //显示上传组件
            this.$refs.uploadimagecom.dialogVisible = true;
            this.action = action;
        },
        //确认按钮传值过来并赋值到form表单上
        childByImageValue: function (childValue) {
            if (this.action == 'videofm') {
                this.form.cover = childValue;
            }
        },
        //确认按钮传值过来并赋值到form表单上
        childByFilesValue: function (childValue) {
            let arr = [];
            for (let i = 0; i < childValue.length; i++) {
                arr.push(childValue[i].id);
            }
            addColumnDownFile({ fileids: arr.toString(), column_id: this.column_id }).then((res) => {
                if (res.code == 1) {
                    this.getFileTableData();
                    this.$message.success('添加下载资料成功');
                } else {
                    this.$message.error('添加下载资料失败');
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.package_wrapper{
    .el-table{
        
    }
}


.handle-box {
    margin-bottom: 20px;
    float: right;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.mr10 {
    margin-right: 10px;
}

.info-image {
    width: 80px;
    border-radius: 4px;
}

.showPay {
    width: 150px;
    margin-right: 10px;
    margin-bottom: 15px;
}

.chooseLecturerTable {
    cursor: pointer;
}

.preview {
    padding: 30px;
    text-align: center;
}

.preview .qrCode {
    margin: 10px 0;
}
</style>

<style>
.el-upload--text {
    border: 0;
    height: 40px;
    text-align: left;
    overflow: unset;
}

.el-upload__tip {
    margin-top: 0;
}

.el-input-group__append {
    background: #e6a23c;
}

.el-input-group__append span {
    color: #fff;
}

.ql-container {
    height: 200px;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 375px !important;
    text-align: center;
}

.avatar-uploader:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
}

.avatar {
    width: 100%;
    display: block;
}
</style>
